package org.wattdepot.cli;

import org.wattdepot.resource.source.jaxb.Source;
import org.wattdepot.util.tstamp.Tstamp;
import org.wattdepot.client.WattDepotClient;
import javax.xml.datatype.XMLGregorianCalendar;
/**
 * Responsible for computing the total power of a source by fuel type.
 * @author Aaron Herres
 */
public class TotalPower implements SingleCommand {
  /**
   * processes the total power command, returns a message.
   * @param client The WattDepotClient to use in connections.
   * @param args The argument string.
   * @return the output message.
  */
  public String processCommand(WattDepotClient client, String[] args) {
    String source;
    XMLGregorianCalendar time;
    String fuelType;
    if (!client.isHealthy()) {
      return Messages.Error.CLIENT_NOT_READY;
    }
    if (args.length < 5) {
      return usageString();
    }
    source = args[1];
    fuelType = args[4];
    try {

      time = Tstamp.makeTimestamp(args[2]);

    }
    catch (Exception e) {

      return Messages.Error.INVALID_TIMESTAMP;

    }
    try {
      Source s = client.getSource(source);
      if (s.isSetVirtual()) {
        return Messages.Error.INVALIDSOURCE;
      }
      if (s.getProperty("fuelType").equalsIgnoreCase(fuelType)) {
        return Double.toString(client.getPowerGenerated(source, time));
      }
      else {
        return Messages.Error.INVALIDPOWERTYPE;
      }
    }
    catch (Exception e) {
      return Messages.Error.CLIENT_NOT_READY;
    }
  }

  /*
   * returns a command-specific usage string.
   * @return usage for this class. 
   * @see org.wattdepot.cli.SingleCommand#usageString()
   */
  @Override
  public String usageString() {
    return "Usage: totalpower <source> <timestamp> fueltype <fueltype>";
  }
}
